<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>员工管理</h3>
    </div>
    <el-form :model="searchForm" ref="searchFormRef" label-width="auto">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="用户名：" prop="name">
            <el-input placeholder="请输入用户名" v-model="searchForm.name" clearable @blur="getData"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号：" prop="phone">
            <el-input placeholder="请输入手机号" v-model="searchForm.phone" clearable @blur="getData"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属角色：" prop="roleId">
            <el-select v-model="searchForm.roleId" placeholder="请选择所属角色" clearable @change="getData">
              <el-option v-for="item in rolesOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button @click="showDialog('add')" v-ripple>添加员工</el-button>

    <art-table :data="tableData" selection :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize"
      :total="pageTotal" @current-change="currentChange" @size-change="sizeChange">
      <template #default>
        <el-table-column label="真实姓名" prop="avatar" #default="scope" width="300px" v-if="columns[0].show">
          <div class="user" style="display: flex; align-items: center">
            <!-- <img class="avatar" :src="scope.row.avatar" /> -->
            <div>
              <p class="user-name">{{ scope.row.nickname }}</p>
              <!-- <p class="email">{{ scope.row.email }}</p> -->
            </div>
          </div>
        </el-table-column>
        <el-table-column label="手机号" prop="username" v-if="columns[1].show" align="center" />

        <el-table-column label="所属角色" prop="roleName" v-if="columns[3].show" align="center" />

        <!-- 改成开关 -->
        <el-table-column label="状态" prop="status" v-if="columns[4].show" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" align="center"
              @click="editStatus(scope.row.id, scope.row.status)" />
          </template>
        </el-table-column>
        <el-table-column label="创建日期" prop="createTime" sortable v-if="columns[5].show" align="center" />
        <el-table-column fixed="right" label="操作" width="150px">
          <template #default="scope">
            <button-table type="edit" @click="showDialog('edit', scope.row)" />
            <button-table type="delete" @click="deleteUser(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加员工' : '编辑员工'" width="30%"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="真实姓名" prop="nickname">
          <el-input v-model="formData.nickname" />
        </el-form-item>
        <el-form-item label="手机号" prop="username">
          <el-input v-model="formData.username" :disabled="!!formData.id" />
        </el-form-item>

        <!-- 登录密码  确认密码 -->
        <el-form-item prop="password" label="登录密码">
          <el-input type="password" v-model="formData.password" show-password />
        </el-form-item>

        <el-form-item label="确认密码" prop="repeatPassword">
          <el-input type="password" v-model="formData.repeatPassword" show-password />
        </el-form-item>

        <el-form-item label="所属角色" prop="roleId">
          <el-select v-model="formData.roleId">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in rolesList" :key="index" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useMenuStore } from '@/store/modules/menu'
import { ACCOUNT_TABLE_DATA } from '@/mock/temp/formData'
import { FormInstance } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import { staffList, AddStaffList, EditStaffList, DelStaffList } from '@/api/driverSchoolApi'
import { RolesList } from '@/api/driverSchoolApi'

const dialogType = ref('add')
const dialogVisible = ref(false)

const formData = reactive({
  username: '', // 手机号
  nickname: '', //真实姓名
  password: '', // 登录密码
  roleId: '', // 所属角色
  repeatPassword: '',
  id: ''
})

const sexOptions = [
  {
    value: '男',
    label: '男'
  },
  {
    value: '女',
    label: '女'
  }
]
const levelOptions = [
  {
    value: '1',
    label: '普通用户'
  },
  {
    value: '2',
    label: ' VIP'
  }
]

const columns = reactive([
  { name: '用户名', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '部门', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])

const searchFormRef = ref<FormInstance>()
const searchForm = reactive({
  name: '',
  phone: '',
  email: '',
  account: '',
  id: '',
  sex: '',
  roleId: '',
  level: ''
})

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type
  console.log(row, 'row===')

  if (type === 'edit' && row) {
    console.log(123)

    formData.id = row.id
    formData.username = row.username
    formData.roleId = row.roleId
    formData.nickname = row.nickname
    formData.password = ''
    formData.repeatPassword = ''
  } else {
    console.log(321)
    formData.repeatPassword = ''
    formData.username = ''
    formData.roleId = ''
    formData.nickname = ''
    formData.password = ''
    formData.id = ''
  }
}

const deleteUser = (id: any) => {
  ElMessageBox.confirm('确定要注销该用户吗？', '注销用户', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await DelStaffList(id)
    if (res.code === '00000') {
      ElMessage.success('注销成功')
      getData()
    }
  })
}

const search = () => {
  getData()
}

const changeColumn = (list: any) => {
  columns.values = list
}

const filterTag = (value: string, row: any) => {
  return row.status === value
}

const getTagType = (status: string) => {
  switch (status) {
    case '1':
      return 'success'
    case '2':
      return 'info'
    case '3':
      return 'warning'
    case '4':
      return 'danger'
    default:
      return 'info'
  }
}

const buildTagText = (status: string) => {
  let text = ''
  if (status === '1') {
    text = '在线'
  } else if (status === '2') {
    text = '离线'
  } else if (status === '3') {
    text = '异常'
  } else if (status === '4') {
    text = '注销'
  }
  return text
}

// 重复密码的验证
const validatePasswordMatch = (rule: any, value: string, callback: (error?: Error) => void) => {
  if (value !== formData.password) {
    callback(new Error('两次密码不一致！'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  nickname: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输登录密码', trigger: 'blur' }],

  repeatPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePasswordMatch, trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择所属角色', trigger: 'change' }
  ]
})

interface rolesLists {
  name: string
  id: string
}
const rolesList = ref<Array<rolesLists>>([])
const rolesOptions = ref<any>([])
async function getRoleList() {
  const res = await RolesList({
    pageNum: 1,
    pageSize: 100,
    keywords: ''
  })
  if (res.code === '00000') {
    rolesList.value = res.data.list
    rolesOptions.value = res.data.list.map((e: any) => {
      return {
        label: e.name,
        value: e.id
      }
    })
  }
}

const formRef = ref<FormInstance>()

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'

      if (dialogType.value === 'add') {
        let res = await AddStaffList({
          username: formData.username,
          nickname: formData.nickname,
          password: formData.password,
          roleId: Number(formData.roleId)
        })
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      } else {
        let res = await EditStaffList(Number(formData.id), {
          username: formData.username,
          nickname: formData.nickname,
          password: formData.password,
          roleId: formData.roleId,
          userId: formData.id
        })
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      }
    }
  })
}

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const tableLoading = ref(false)
async function getData() {
  try {
    tableLoading.value = true

    const { code, data } = await staffList(filterEmptyValues({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      nickname: searchForm.name,
      username: searchForm.phone,
      roleId: searchForm.roleId
    }))
    if (code === '00000') {
      tableData.value = data.list
      pageTotal.value = data.total
      console.log(tableData.value, 'tableData.value')
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}
const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

interface rolesLists {
  name: string
  id: string
}
async function editStatus(id: any, status: number) {
  console.log(status, 'status===')

  try {
    const res = await EditStaffList(id, {
      status: Number(status)
    })
  } catch (e) {
  } finally {
    await getData()
  }
}
onMounted(() => {
  getData()
  getRoleList()
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .user {
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 6px;
    }

    >div {
      margin-left: 10px;

      .user-name {
        font-weight: 500;
        color: var(--art-text-gray-800);
      }
    }
  }
}
</style>
